package com.wf.smartcomm.server.client.action;

import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ModelDriven;
import com.wf.smartcomm.server.apns.IApnsService;
import com.wf.smartcomm.server.apns.model.Payload;
import com.wf.smartcomm.server.bean.House;
import com.wf.smartcomm.server.bean.UnLockReport;
import com.wf.smartcomm.server.bean.UnitMachine;
import com.wf.smartcomm.server.bean.User;
import com.wf.smartcomm.server.bean.Village;
import com.wf.smartcomm.server.model.PushMessage;
import com.wf.smartcomm.server.push.Pusher;
import com.wf.smartcomm.server.response.ResponseCode;
import com.wf.smartcomm.server.response.ResponseMessage;
import com.wf.smartcomm.server.service.HouseService;
import com.wf.smartcomm.server.service.UnLockReportService;
import com.wf.smartcomm.server.service.UnitMachService;
import com.wf.smartcomm.server.service.UserService;
import com.wf.smartcomm.server.service.VillageService;
import com.wf.smartcomm.server.util.ConstantUtils;
import com.wf.smartcomm.server.util.IdUtils;
import com.wf.smartcomm.server.util.PushUtils;
import com.wf.smartcomm.server.util.StringUtil;

/** 
 * @author 38884306@qq.com  
 * @version 创建时间：2015-6-4 上午10:23:37 
 * 
 */
@Controller
@Scope("prototype")
public class UnitMachineAction extends BaseAction implements ModelDriven<UnitMachine>{
	
	private UnitMachine um = new UnitMachine();
	
	private static Logger logger = Logger.getLogger(UnitMachineAction.class);
	
	@Resource
	private UnitMachService unitMachServiceImpl;
	@Resource
	private UserService userServiceImpl;
	
	@Resource
	private HouseService houseServiceImpl;
	
	@Resource
	private VillageService villageService;
	
	@Resource
	private UnLockReportService unLockReportService;
	
	public void getUser() throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String hardId = request.getParameter("hardId");
		UnitMachine um = unitMachServiceImpl.getByHardId(hardId);
		if (um == null) {
			logger.info("um hardware id not exist ----------> "+hardId);
			map.put("code", ResponseCode.UM_HARDWAREID_WRONG);
			map.put("data", ResponseMessage.UM_HARDWAREID_WRONG);
			printJsonData(gson.toJson(map));
			return;
		}
		
		User user = um.getUser();
		if (StringUtil.isEmpty(um.getVoipNumber())) {
			HashMap<String, Object> result = null;
			CCPRestSDK restAPI = new CCPRestSDK();
			if (PushUtils.isDevEnv) {
				restAPI.init("sandboxapp.cloopen.com", "8883");
				restAPI.setAccount("8a48b551516c09cd01516c36b1cf00dd", "a989200a4e29483cb3e5d6107ae9fdd0");
				restAPI.setAppId("aaf98f89516bf50b015180a2d42a2875");
			} else {
				restAPI.init(PushUtils.pushConfig.getProperty("CloudAddress"), PushUtils.pushConfig.getProperty("CloudPort"));// 初始化服务器地址和端口，格式如下，服务器地址不需要写https://
				restAPI.setAccount(PushUtils.pushConfig.getProperty("CloudMainAccount"), PushUtils.pushConfig.getProperty("CloudMainToken"));// 初始化主帐号和主帐号TOKEN
				restAPI.setAppId(PushUtils.pushConfig.getProperty("CloudAppId"));// 初始化应用ID
			}
			result = restAPI.createSubAccount(user.getObjectId());
			System.out.println("SDKTestCreateSubAccount result=" + result);
			if("000000".equals(result.get("statusCode"))){
				//正常返回输出data包体信息（map）
				HashMap<String,Object> data = (HashMap<String, Object>) result.get("data");
				List<HashMap<String,Object>> object =  (List<HashMap<String,Object>>) data.get("SubAccount");
				for (HashMap<String, Object> hashMap : object) {
					if (hashMap.containsKey("subAccountSid")) {
						user.setSubAccountSid(hashMap.get("subAccountSid").toString());
					}
					if (hashMap.containsKey("voipAccount")) {
						user.setVoipAccount(hashMap.get("voipAccount").toString());
						um.setVoipNumber(hashMap.get("voipAccount").toString());
					}
					if (hashMap.containsKey("voipPwd")) {
						user.setVoipPwd(hashMap.get("voipPwd").toString());
					}
					if (hashMap.containsKey("subToken")) {
						user.setSubToken(hashMap.get("subToken").toString());
					}
				}
				unitMachServiceImpl.update(um);
				userServiceImpl.update(user);
				map.put("code", ResponseCode.OK);
				map.put("data", user);
			}else{
				//异常返回输出错误码和错误信息
				System.out.println("错误码=" + result.get("statusCode") +" 错误信息= "+result.get("statusMsg"));
				map.put("code", result.get("statusCode"));
				map.put("data", result.get("statusMsg"));
			}
		}else {
			map.put("code", ResponseCode.OK);
			map.put("data", user);
		}
		
		printJsonData(gson.toJson(map));
	}
	
	public void sendPhoto() throws Exception{
		String url = request.getParameter("url");
		String userId = request.getParameter("userId");
		User user = userServiceImpl.getUserById(userId);
		if (user.getDeviceType().equals(ConstantUtils.DEVICE_TYPE_APPLE)) {
			IApnsService service = PushUtils.getApnsService();
			Payload payload = new Payload();
			//payload.setAlert("");
			payload.setBadge(0);
			//payload.setSound("default");
			payload.addParam("url", url);
			payload.addParam("type", ConstantUtils.PUSH_TYPE_SEND_PHOTO);
			service.sendNotification(user.getAppleToken(), payload);
			return;
		}
		Pusher pusher = PushUtils.getClientPusher();
		PushMessage pMsg = new PushMessage();
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_NEW_SEND_PHOTO);
		pMsg.setData(url.substring(url.lastIndexOf("/")+1, url.lastIndexOf(".jpg")));
		boolean result = pusher.push0x20Message(user.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pMsg.setPushType(ConstantUtils.PUSH_TYPE_SEND_PHOTO);
		pMsg.setData(url);
		pusher.push0x20Message(user.getPushId().getBytes(), gson.toJson(pMsg).getBytes());
		pusher.close();
		if (result) {
			logger.info("sendPhoto msg send success: userId="+userId+" photoUrl="+url);
		}else {
			logger.info("sendPhoto msg send fail");
		}
		
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
	public void get() throws Exception{
		String hardId = request.getParameter("hardId");
		logger.info("getUm hardware id ----------> "+hardId);
		UnitMachine um = unitMachServiceImpl.getByHardId(hardId);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		map.put("data", um);
		printJsonData(gson.toJson(map));
	}
	
	public void update() throws Exception{
		UnitMachine sourceUm = unitMachServiceImpl.getById(um.getObjectId());
		sourceUm.update(um);
		unitMachServiceImpl.update(sourceUm);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}	
	
	public void getHouse()throws Exception{
		HashMap<String, Object> map = new HashMap<String, Object>();
		String mid = request.getParameter("mid");
		String number = request.getParameter("number");
		UnitMachine um = unitMachServiceImpl.getById(mid);
		if (!um.getType().equals("1")) {
			map.put("code", ResponseCode.UM_TYPE_ERROR);
			map.put("data", ResponseMessage.UM_TYPE_ERROR);
			printJsonData(gson.toJson(map));
			return;
		}
		House house = houseServiceImpl.getByUmInfo(um, number);
		map.put("code", ResponseCode.OK);
		map.put("data", house);
		printJsonData(gson.toJson(map));
	}
	
	public void report() throws Exception{
		unitMachServiceImpl.report(um);
		HashMap<String, Object> map = new HashMap<String, Object>();
		map.put("code", ResponseCode.OK);
		printJsonData(gson.toJson(map));
	}
	
/*     */   public void push() throws Exception {
/*  74 */     String uid = this.request.getParameter("uid");
/*  75 */     User user = this.userServiceImpl.getUserById(uid);
/*  76 */     IApnsService service = PushUtils.getApnsService();
/*  77 */     Payload payload = new Payload();
/*  78 */     payload.setAlert("单元机呼叫");
/*  79 */     payload.setBadge(1);
/*  80 */     payload.setSound("sub.caf");
/*  81 */     payload.addParam("type", 10);
/*  82 */     service.sendNotification(user.getAppleToken(), payload);
/*  83 */     HashMap<String,Object> map = new HashMap<String,Object>();
/*  84 */     map.put("code", 200);
/*  85 */     printJsonData(this.gson.toJson(map));
/*     */   }
/*     */ 

	public void list() throws Exception {
		String vid = request.getParameter("vid");
		Village village = new Village(vid);
		
		unitMachServiceImpl.listAllByVillage(village, page);
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		//dataMap.put("sEcho",initEcho);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(gson.toJson(dataMap));
	}
	
	public void listUn() throws Exception {
		unitMachServiceImpl.listAllUn(page);
		int count = page.getTotalCount();
		HashMap<String, Object> dataMap = new HashMap<String, Object>();
		dataMap.put("iTotalRecords", count);
		dataMap.put("iTotalDisplayRecords", count);
		dataMap.put("aaData", page.getDataList());
		printJsonData(gson.toJson(dataMap));
	}
	
	public void callCenter()throws Exception{
		String vid = request.getParameter("vid");
		User user = userServiceImpl.getCenterUser(vid);
		 HashMap<String,Object> map = new HashMap<String,Object>();
		 map.put("code", 200);
		 map.put("data", user);
		 printJsonData(gson.toJson(map));
	}
	
	public void unlock()throws Exception{
		String unlockJson = request.getParameter("unlockJson");
		UnLockReport unLockReport = new Gson().fromJson(unlockJson, UnLockReport.class);
		unLockReport.setObjectId(IdUtils.uuid());
		unLockReport.setCreatedAt(new Date());
		unLockReportService.save(unLockReport);
		 HashMap<String,Object> map = new HashMap<String,Object>();
		 map.put("code", 200);
		 printJsonData(gson.toJson(map));
	}
	
	public void listHouse()throws Exception{
		 List<House> houses = houseServiceImpl.listByUm(um);
		 HashMap<String,Object> map = new HashMap<String,Object>();
		 map.put("code", 200);
		 map.put("data", houses);
		 printJsonData(gson.toJson(map));
	}
	
	@Override
	public UnitMachine getModel() {
		return um;
	}
}
